# -*- coding:utf-8 -*-
from flask import Flask, render_template, request, flash, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_login import LoginManager, login_user, logout_user, current_user, login_required
from markdown import markdown
from markupsafe import Markup

from models import db, User, Student
from forms import LoginForm, RegisterForm, StudentForm, StudentSearchForm
from utils import get_md5, get_log, set_log
from api import random_picture

app = Flask(__name__)

# 设置 flask_sqlalchemy 需要的配置
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SECRET_KEY'] = 'asdgjasdkgjasdl;fmsdkgajkskgjsdgklasjkglajkgasjgklas' # 随便来一个

# 使用 flask_bootstrap
Bootstrap(app)
# 使用 flask_sqlalchemy 来管理数据库
db.init_app(app)
db.create_all(app=app)
# 使用 flask_login
login_manager = LoginManager()
login_manager.init_app(app=app)
login_manager.login_view = 'user_login'
login_manager.login_message = '请先登录或注册'
@login_manager.user_loader
def get_user(uid):
    return User.query.get(int(uid))


@app.route('/')
def index():
    extensions = ['markdown.extensions.extra', 'markdown.extensions.codehilite','markdown.extensions.tables','markdown.extensions.toc']
    with open('readme.md',encoding='utf-8') as f:
        md_text = f.read()
    html = markdown(md_text,extensions=extensions)
    description = Markup(html)
    return render_template('index.html', description=description)


@app.route('/log/view')
def log_view():
    logs = get_log()
    return render_template('log_view.html', logs=logs)



@app.route('/user/register', methods=['get', 'post'])
def user_register():
    if request.method == 'GET':
        form = RegisterForm()
        return render_template('user/register.html', form=form)
    elif request.method == 'POST':
        form = RegisterForm(request.form)
        if form.validate():
            password = get_md5(form.password.data.encode('utf8'))
            user = User(
                username=form.username.data,
                password=password
            )
            if user.query.first():
                flash('用户名 {} 已经注册啦，你需要换个名字了'.format(form.username.data))
                return render_template('user/register.html', form=form)
            db.session.add(user)
            db.session.commit()
            flash('注册成功，请使用 {} 登录'.format(form.username.data))
            set_log('注册成功')
            return redirect(url_for('user_login'))
        set_log('注册失败')
        return render_template('user/register.html', form=form)


@app.route('/user/login', methods=['get', 'post'])
def user_login():
    if request.method == 'GET':
        if current_user.is_authenticated:
            flash('已经登录了，不需要重复登录')
            return redirect(url_for('index'))
        form = LoginForm()
        next = request.args.get('next', url_for('index'))
        return render_template('user/login.html', form=form, next=next)
    elif request.method == 'POST':
        form = LoginForm(request.form)
        if form.validate():
            password = get_md5(form.password.data.encode('utf8'))
            user = User.query.filter_by(username=form.username.data, password=password).first()
            if user:
                login_user(user)
                next = request.args.get('next')
                if not next or not next.startswith('/'): # 防止重定向攻击
                    next = url_for('index')
                set_log('登录成功')
                return redirect(next)
            else:
                set_log('登录失败')
                flash('用户名不存在 或 密码不正确')
                return render_template('user/login.html', form=form)
        set_log('登录失败')
        return render_template('user/login.html', form=form)

@app.route('/user/logout')
def user_logout():
    logout_user()
    return redirect(url_for('user_login'))

@app.route('/need_login')
@login_required
def need_login():
    return '登录你就能看到这句话了'

@app.route('/student/list')
@app.route('/student/search', methods=['get', 'post'])
def student_list():
    if request.method == 'GET':
        students = Student.query.all()
        form = StudentSearchForm()
        return render_template('student/list.html', students=students, form=form)
    elif request.method == 'POST':
        form = StudentSearchForm(request.form)
        if form.validate():
            students = Student.query.filter_by(name=form.name.data).all()
            set_log('学生搜索成功')
            return render_template('student/list.html', students=students, form=form)
        else:
            set_log('学生搜索失败')
            return redirect(url_for('student_list'))

@app.route('/student/add', methods=['get', 'post'])
@login_required
def student_add():
    if request.method == 'GET':
        form = StudentForm()
        return render_template('student/add.html', form=form)
    elif request.method == 'POST':
        form = StudentForm(request.form)
        if form.validate():
            student = Student(
                name=form.name.data,
                gender=form.gender.data,
                class_name=form.class_name.data
            )
            db.session.add(student)
            db.session.commit()
            flash('添加成功')
            set_log('学生添加成功')
            return redirect(url_for('student_detail', idx=student.id))
        else:
            set_log('学生添加失败')
            return render_template('student/add.html', form=form)


@app.route('/student/detail/<int:idx>')
@login_required
def student_detail(idx):
    student = Student.query.get(idx)
    if student:
        return render_template('student/detail.html', student=student, idx=idx)
    else:
        flash('学生不存在，不要自己构造页面哦')
        return redirect(url_for('student_list'))

@app.route('/student/update/<int:idx>', methods=['get', 'post'])
@login_required
def student_update(idx):
    if request.method == 'GET':
        student = Student.query.get(idx)
        if student:
            form = StudentForm(obj=student)
        return render_template('student/update.html', form=form, idx=idx)
    elif request.method == 'POST':
        form = StudentForm(request.form)
        if form.validate():
            student = Student.query.get(idx)
            if student:
                student.name = form.name.data
                student.gender = form.gender.data
                student.class_name = form.class_name.data
                db.session.add(student)
                db.session.commit()
                set_log('学生修改成功')
                return redirect(url_for('student_detail', idx=idx))
            else:
                set_log('学生修改失败')
                flash('请不要自己构造页面提交')
                return redirect(url_for('student_list'))
        else:
            set_log('学生修改失败')
            return render_template('student/update.html', form=form, idx=idx)

@app.route('/student/delete/<int:idx>')
@login_required
def student_delete(idx):
    student = Student.query.get(idx)
    if student:
        db.session.delete(student)
        db.session.commit()
    return redirect(url_for('student_list'))

@app.route('/explore')
def explore():
    pic_url = random_picture()
    return render_template('explore.html', pic_url=pic_url)





if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)